package cn.bone.demo02;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.time.FastDateFormat;

import java.util.Date;

/**
 * Created by Administrator on 2018/1/29.
 */
public class DoorClientHandler extends ChannelInboundHandlerAdapter {

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端消息:连接服务器成功");
        closeDoor(ctx,2);
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
        System.out.println("客户端消息:断开与服务器的连接 "+format.format(new Date()));
    }

    /**
     * 读取数据
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
        String hex = ByteUtil.bytes2Hex2(req);
        Byte event = req[2];
        String eventStr = "";
        /**心跳*/
        if(event.intValue()==0x56){
            eventStr = "心跳";
            heartbeatAnswer(ctx);
        }
        /**刷卡*/
        else if(event.intValue()==0x53){
            eventStr = "刷卡事件";
            brushCardAnswer(ctx,req);
        }
        /**远程开门响应*/
        else if(event.intValue()==0x2c){
            String result;
            if(req[7]==0x06){
                result = "成功";
            }else{
                result = "失败";
            }
            eventStr = "远程开门<"+result+">";
        }
        /**远程关门响应*/
        else if(event.intValue()==0x2e){
            String result;
            if(req[7]==0x06){
                result = "成功";
            }else{
                result = "失败";
            }
            eventStr = "远程关门<"+result+">";
        }
        System.out.println(eventStr +": "+ hex);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("出现异常:"+cause.getMessage());
        ctx.close();
    }

    /**
     * 心跳
     */
    private void heartbeatAnswer(ChannelHandlerContext ctx){
        ByteBuf byteBuf = Unpooled.copiedBuffer(ByteUtil.heartbeatAnswer());
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 刷卡事件
     */
    private void brushCardAnswer(ChannelHandlerContext ctx,byte[] req){

        // 门id
        int doorId = ((Byte)req[4]).intValue();
        // 流水id
        int brushId = ((Byte)req[20]).intValue();

        System.out.println("门id:"+doorId);
        System.out.println("流水id:"+brushId);

        String cardId = ByteUtil.getCardId(req[10],req[9],req[8],req[7]);
        System.out.println("门卡:" + cardId);

        ByteBuf byteBuf = Unpooled.copiedBuffer(ByteUtil.brushCardAnswer(doorId,brushId));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 开门
     */
    private void openDoor(ChannelHandlerContext ctx,int doorId){
        Integer[] ints = {0x02,0xa0,0x2c,0xff,doorId,0x00,0x00};
        byte[] bytes = ByteUtil.getBytes(ints);
        String s = ByteUtil.bytes2Hex2(bytes);
        System.out.println("开门<"+doorId+">:"+s);
        ByteBuf resp = Unpooled.copiedBuffer(bytes);
        ctx.writeAndFlush(resp);
    }

    /**
     * 关门
     */
    private void closeDoor(ChannelHandlerContext ctx,int doorId){
        Integer[] ints = {0x02,0xa0,0x2e,0xff,doorId,0x00,0x00};
        byte[] bytes = ByteUtil.getBytes(ints);
        String s = ByteUtil.bytes2Hex2(bytes);
        System.out.println("关门<"+doorId+">:"+s);
        ByteBuf resp = Unpooled.copiedBuffer(bytes);
        ctx.writeAndFlush(resp);
    }

    private void printInfo(byte[] bytes){
        Byte b_year = bytes[8];
        int year = b_year.intValue() + 2000;
        Byte b_month = bytes[9];
        int month = b_month.intValue();
        Byte b_day = bytes[10];
        int day = b_day.intValue();
        Byte b_hour = bytes[11];
        int hour = b_hour.intValue();
        Byte b_minute = bytes[12];
        int minute = b_minute.intValue();
        Byte b_second = bytes[13];
        int second = b_second.intValue();
        //门状态
        Byte b_doorState = bytes[14];
        int doorState = b_doorState.intValue();

        //功能
        Byte b_function = bytes[15];
        int function = b_function.intValue();

        //卡最大id
        Byte b_maxId1 = bytes[16];
        Byte b_maxId2 = bytes[17];
        int maxId1 = b_maxId1.intValue();
        int maxId2 = b_maxId2.intValue();

        //刷卡数量
        Byte b_brushCardCount1 = bytes[18];
        Byte b_brushCardCount2 = bytes[19];
        int brushCardCount1 = b_brushCardCount1.intValue();
        int brushCardCount2 = b_brushCardCount2.intValue();

        //报警数量
        Byte b_alarmCount1 = bytes[20];
        Byte b_alarmCount2 = bytes[21];
        int alarmCount1 = b_alarmCount1.intValue();
        int alarmCount2 = b_alarmCount2.intValue();

        //假日数量
        Byte b_holidayCount = bytes[22];
        int holidayCount = b_holidayCount.intValue();

        //版本
        Byte b_version = bytes[23];
        int version = b_version.intValue();

        //包尾
        Byte v_validate = bytes[24];
        int validate = v_validate.intValue();
        Byte v_end = bytes[25];
        int end = v_end.intValue();
        System.out.println("心跳--"+year+"年"+month+"月"+day+"日 "+hour+":"+minute+":"+second);
        System.out.println(
                "状态:"+doorState
                +" 功能:"+function
                +" 卡最大id"+maxId1+"_"+maxId2
                +" 刷卡数量"+brushCardCount1+"_"+brushCardCount2
                +" 报警数量"+alarmCount1+"_"+alarmCount2
                +" 假日数量"+holidayCount
                +" 版本"+version
                +" 校验"+validate
                +" end"+end
        );
    }

}
